﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tools.DA.Repository;
using Tools.Domain;

namespace Tools.DA
{
    public class UnitOfWork<TContext> : IDisposable, IUnitOfWork
             where TContext : ContextBase, new()
    {
        private TContext _context;
        private Dictionary<Type, object> _repositories;
        //private bool _disposed;

        public UnitOfWork()
        {
            _context = new TContext();
            _repositories = new Dictionary<Type, object>();
            //_disposed = false;
        }

        public IRepository<TEntity> GetRepository<TEntity>() where TEntity : EntityBase
        {
            if (!_repositories.Keys.Contains(typeof(TEntity)))
                _repositories.Add(typeof(TEntity), new Repository<TEntity>(_context));
            return _repositories[typeof(TEntity)] as IRepository<TEntity>;
        }

        public void Save()
        {
            _context.SaveChanges();
        }

        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    _context.Dispose();
                }
            }
            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}
